<template>
  <div :class="role === 'admin' ? 'navbar' : 'navbar navbar-dcotor'">
    <div class="left-side">
      <a-space>
        <img alt="logo" src="@/assets/images/logo-jy.png" />
        <a-typography-title
          :style="{ margin: 0, fontSize: '18px' }"
          :heading="5"
          class="logo-title"
        >
          融影标注系统
        </a-typography-title>
      </a-space>
    </div>
    <ul class="right-side">
      <li>
        <a-dropdown
          :popup-visible="visible"
          trigger="hover"
          :style="{ cursor: 'pointer' }"
          @popup-visible-change="handleChange"
        >
          <div class="dropdown-box">
            <!-- <a-avatar
              :size="32"
              :style="{ marginRight: '8px', cursor: 'pointer' }"
            >
              <img alt="avatar" :src="avatar" />
            </a-avatar> -->
            <div class="avatar">
              <i class="iconfont icon-touxiang"></i>
            </div>
            <span class="user-name" :style="{ cursor: 'pointer' }">{{ userName }}</span>
            <icon-down v-if="!visible" :style="{ cursor: 'pointer' }" />
            <icon-up v-else :style="{ cursor: 'pointer' }" />
          </div>

          <template #content>
            <a-doption v-show="role === 'user'">
              <a-space @click="goDoctorHome">
                <span>我的主页</span>
              </a-space>
            </a-doption>
            <a-doption v-if="role === 'user'" v-role="'A000000000'">
              <a-space @click="switchRoles">
                <span>切换到管理员</span>
              </a-space>
            </a-doption>
            <a-doption v-if="role === 'admin'" v-role="'B000000000'">
              <a-space @click="switchRoles">
                <span>切换到标注医生</span>
              </a-space>
            </a-doption>

            <a-doption>
              <a-space @click="handleUpdatePasswordClick">
                <span>
                  {{ $t("messageBox.userUpdatePassword") }}
                </span>
              </a-space>
            </a-doption>
            <a-doption>
              <a-space @click="handleLogout">
                <span>
                  {{ $t("messageBox.logout") }}
                </span>
              </a-space>
            </a-doption>
          </template>
        </a-dropdown>
      </li>
    </ul>
  </div>
  <!-- 修改密码弹窗 -->
  <Dialog
    :visible="dialogVisible"
    :title="'修改密码'"
    :width="440"
    :maskClosable="false"
    :okText="'保存'"
    :isForm="true"
    @update:visible="handleVisible"
  >
    <template v-slot>
      <div class="dialog-body">
        <a-form :model="passwordForm" ref="formRef" auto-label-width>
          <!-- <a-space direction="vertical" fill> -->
          <a-form-item
            field="oldPwd"
            label="原始密码"
            :validate-trigger="['input', 'blur']"
          >
            <a-input-password
              v-model.trim="passwordForm.oldPwd"
              :style="{ width: '272px', height: '32px' }"
              placeholder="请输入您的原始密码"
              allow-clear
            />
          </a-form-item>
          <a-form-item
            field="newPwd"
            label="新密码"
            :validate-trigger="['input', 'blur']"
            :rules="[
              { required: true, type: 'string', message: '新密码不能为空' },
              { minLength: 6, message: '密码不能少于6位' },
              {
                match: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/,
                message: '密码格式不正确',
              },
            ]"
          >
            <a-input-password
              v-model.trim="passwordForm.newPwd"
              :style="{ width: '272px', height: '32px' }"
              placeholder="请设置6-16位新密码"
              :max-length="16"
              allow-clear
            />
          </a-form-item>
          <a-form-item
            field="againPassword"
            label="确认新密码"
            class="submit-password"
            :rules="[
              { required: true, type: 'string', message: '确认新密码不能为空' },
              {
                match: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/,
                message: '密码格式不正确',
              },
            ]"
            :validate-trigger="['input', 'blur']"
          >
            <a-input-password
              v-model.trim="passwordForm.againPassword"
              :style="{ width: '272px', height: '32px' }"
              placeholder="请再次输入您的新密码"
              :max-length="16"
              allow-clear
            />
          </a-form-item>
          <!-- </a-space> -->
        </a-form>
      </div>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { computed, ref, inject, reactive } from "vue";
import { useRouter } from "vue-router";
import { Message } from "@arco-design/web-vue";
import { useAppStore, useUserStore } from "@/store";
import { changePassword as ChangePassword } from "@/api/user/user";
// import { LOCALE_OPTIONS } from '@/locale';
import useUser from "@/hooks/user";
import usePermission from "@/hooks/permission";
import type { CallBackData } from "@/components/dialog/type.d";
// import MessageBox from '../message-box/index.vue';
import Dialog from "@/components/dialog/index.vue";
import md5 from "md5";
import { appRoutes } from "@/router/routes";

// interface Prop {
//   avatar: string;
//   userName: string;
//   role: string;
//   switchRole: Function;
//   id: number;
// }

// const props = defineProps<Prop>();
const router = useRouter();
// const routes = inject<any>("secondRoute");
const visible = ref(false);
const dialogVisible = ref(false);
const passwordForm = ref({
  oldPwd: "",
  newPwd: "",
  againPassword: "",
});
const formRef = ref();

const userStore = useUserStore();
const Permission = usePermission();
const { logout } = useUser();
// const locales = [...LOCALE_OPTIONS];
const avatar = computed(() => userStore.userName);
const userName = computed(() => userStore.userName);
const role = computed(() => userStore.role);
// 登出
const handleLogout = () => {
  logout();
};
// 回到医生主页
const goDoctorHome = () => {
  router.push({
    path: "/doctor/doctorHome",
  });
};
// 切换权限
const switchRoles = async () => {
  const res = await userStore.switchRoles();
  // let current = "";
  // while (routes.length) {
  //   const firstElement = routes.shift();
  //   if (Permission.permissionRouter(firstElement)) {
  //     current = firstElement.name;
  //     break;
  //   }
  // }
  const current = Permission.findFirstPermissionRoute(appRoutes, userStore.role);
  router.push({
    name: res === "admin" ? current?.name : "DoctorHome",
  });
};
// 修改密码
const handleUpdatePasswordClick = () => {
  dialogVisible.value = true;
};
// 切换下拉菜单状态
const handleChange = (flag: boolean) => {
  visible.value = flag;
};

// 获取子组件点击按钮值
const handleVisible = async (data: CallBackData) => {
  if (data.status === "save") {
    const res = await formRef.value.validate();
    data.done(true);
    if (res !== undefined) {
      if (passwordForm.value.newPwd !== passwordForm.value.againPassword) {
        formRef.value.setFields({
          againPassword: {
            status: "error",
            message: "确认新密码与新密码不同",
          },
        });
      }
    } else {
      if (passwordForm.value.newPwd !== passwordForm.value.againPassword) {
        formRef.value.setFields({
          againPassword: {
            status: "error",
            message: "确认新密码与新密码不同",
          },
        });
      } else {
        if (passwordForm.value.oldPwd === passwordForm.value.newPwd) {
          formRef.value.setFields({
            newPwd: {
              status: "error",
              message: "新旧密码一致",
            },
          });
        } else {
          const { againPassword, oldPwd, newPwd } = passwordForm.value;
          const res = await ChangePassword({
            id: userStore.id,
            type: "2", //修改密码业务
            oldPwd: md5(oldPwd),
            newPwd: md5(newPwd),
          });
          Message.success("修改成功");
          formRef.value.resetFields();
          dialogVisible.value = data.flag;
          setTimeout(() => {
            handleLogout();
          }, 1000);
        }
      }
    }
  } else if (data.status === "clear") {
    formRef.value.resetFields();
    dialogVisible.value = data.flag;
  }
};
</script>

<style scoped lang="less">
.navbar {
  display: flex;
  justify-content: space-between;
  background-color: #fff;
  // background-color: #000;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 100;
  width: 100%;
  height: 56px;
  &.navbar-dcotor {
    .right-side {
      background-color: #1f474c;
      color: #fff;
      margin: 0;
    }
    .arco-icon {
      color: #fff;
    }
  }
}

.left-side {
  display: flex;
  align-items: center;
  padding-left: 20px;
  padding-right: 18px;
  width: 100%;
  flex: 1;
  background-color: #1f474c;
  flex-flow: nowrap;
  min-width: 220px;
  max-width: 220px;
  .logo-title {
    color: #fff;
  }
}

.right-side {
  display: flex;
  padding-right: 20px;
  list-style: none;
  justify-content: flex-end;
  flex: 9;
  :deep(.locale-select) {
    border-radius: 20px;
  }
  li {
    display: flex;
    align-items: center;
    padding: 0 10px;
  }

  a {
    color: var(--color-text-1);
    text-decoration: none;
  }
  .user-name {
    padding-right: 8px;
  }
  .dropdown-box {
    display: flex;
    align-items: center;
  }
  .avatar {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    margin-right: 13px;
    display: inline-block;
    color: #ccc;
    i {
      font-size: 28px;
    }
  }
}
.submit-password {
  :deep(.arco-form-item-label-col > .arco-form-item-label) {
    white-space: nowrap;
  }
}
</style>

<style lang="less">
.message-popover {
  .arco-popover-content {
    margin-top: 0;
  }
}
</style>
